package com.example.network_sdk;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
    private String BASE_URL=BuildConfig.BASE_URL;
    public RetrofitManager() {
    }
    private static volatile RetrofitManager instance=null;
    public static RetrofitManager getInstance(){
        if (instance==null){
            synchronized (RetrofitManager.class){
                if (instance==null){
                    instance=new RetrofitManager();
                }
            }
        }
        return instance;
    }
    private Retrofit retrofit;
    private void create(){
        retrofit=new Retrofit.Builder()
                .client(new OkHttpClient.Builder()
                        .readTimeout(1, TimeUnit.MINUTES)
                        .writeTimeout(1, TimeUnit.MINUTES)
                        .connectTimeout(1,TimeUnit.MINUTES)
                        .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                        .addInterceptor(new Interceptor() {
                            @Override
                            public Response intercept(Chain chain) throws IOException {
                                Request request = chain.request().newBuilder().addHeader("appversion", "1.0").build();
                                return chain.proceed(request);
                            }
                        })

                        .build())
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    public Retrofit getRetrofit(){
        if (retrofit==null){
            create();
        }
        return retrofit;
    }

}
